from fastapi import APIRouter, Depends, HTTPException, Query
from sqlalchemy.orm import Session
from typing import Dict, Any, List, Optional
from datetime import datetime
import json

from app.api import deps
from app.core.quota_manager import quota_manager, QuotaType, QuotaStatus
from pydantic import BaseModel

router = APIRouter()

class QuotaCheckRequest(BaseModel):
    quota_type: str
    requested_amount: float

class BatchQuotaCheckRequest(BaseModel):
    checks: List[QuotaCheckRequest]

class TaskQuotaEstimateRequest(BaseModel):
    service_type: str  # video_generation, image_generation, etc.
    duration: Optional[int] = 10
    resolution: Optional[str] = "1280x720"
    provider: Optional[str] = None
    params: Optional[Dict[str, Any]] = {}

@router.get("/quotas/summary")
async def get_quota_summary(
    current_user = Depends(deps.get_current_user)
):
    """获取用户配额总览"""
    
    try:
        # 检查用户是否为VIP（这里需要根据实际用户模型调整）
        is_vip = getattr(current_user, 'is_vip', False)
        
        summary = quota_manager.get_quota_summary(current_user.id, is_vip)
        
        return {
            "success": True,
            "data": summary
        }
        
    except Exception as e:
        raise HTTPException(status_code=500, detail=f"获取配额总览失败: {str(e)}")

@router.get("/quotas/{quota_type}")
async def get_quota_detail(
    quota_type: str,
    period: str = Query("daily", description="时间周期: daily, monthly, current"),
    current_user = Depends(deps.get_current_user)
):
    """获取特定配额详情"""
    
    try:
        # 验证配额类型
        try:
            quota_enum = QuotaType(quota_type)
        except ValueError:
            raise HTTPException(status_code=400, detail=f"无效的配额类型: {quota_type}")
        
        is_vip = getattr(current_user, 'is_vip', False)
        
        # 获取配额限制
        quotas = quota_manager.get_user_quotas(current_user.id, is_vip)
        limit = quotas.get(quota_enum, 0)
        
        # 获取使用量数据
        usage_data = quota_manager.get_current_usage(current_user.id, quota_enum, period)
        
        # 计算状态
        current_usage = usage_data["current_usage"]
        usage_percentage = current_usage / limit if limit > 0 else 0
        
        warning_threshold = quota_manager.warning_thresholds.get(quota_enum, 0.8)
        
        if current_usage >= limit:
            status = QuotaStatus.EXCEEDED.value
        elif usage_percentage >= warning_threshold:
            status = QuotaStatus.WARNING.value
        else:
            status = QuotaStatus.AVAILABLE.value
        
        return {
            "success": True,
            "data": {
                "quota_type": quota_type,
                "period": period,
                "limit": float(limit) if hasattr(limit, '__float__') else limit,
                "current_usage": current_usage,
                "remaining": max(0, limit - current_usage),
                "usage_percentage": usage_percentage,
                "status": status,
                "warning_threshold": warning_threshold,
                "usage_data": usage_data
            }
        }
        
    except HTTPException:
        raise
    except Exception as e:
        raise HTTPException(status_code=500, detail=f"获取配额详情失败: {str(e)}")

@router.post("/quotas/check")
async def check_quota(
    request: QuotaCheckRequest,
    current_user = Depends(deps.get_current_user)
):
    """检查单个配额是否足够"""
    
    try:
        # 验证配额类型
        try:
            quota_enum = QuotaType(request.quota_type)
        except ValueError:
            raise HTTPException(status_code=400, detail=f"无效的配额类型: {request.quota_type}")
        
        is_vip = getattr(current_user, 'is_vip', False)
        
        result = quota_manager.check_quota(
            current_user.id, 
            quota_enum, 
            request.requested_amount, 
            is_vip
        )
        
        return {
            "success": True,
            "data": result
        }
        
    except HTTPException:
        raise
    except Exception as e:
        raise HTTPException(status_code=500, detail=f"检查配额失败: {str(e)}")

@router.post("/quotas/check-batch")
async def check_batch_quota(
    request: BatchQuotaCheckRequest,
    current_user = Depends(deps.get_current_user)
):
    """批量检查多个配额"""
    
    try:
        is_vip = getattr(current_user, 'is_vip', False)
        
        # 转换请求格式
        checks = []
        for check in request.checks:
            # 验证配额类型
            try:
                QuotaType(check.quota_type)  # 验证有效性
            except ValueError:
                raise HTTPException(status_code=400, detail=f"无效的配额类型: {check.quota_type}")
            
            checks.append({
                "quota_type": check.quota_type,
                "requested_amount": check.requested_amount
            })
        
        result = quota_manager.check_multiple_quotas(current_user.id, checks, is_vip)
        
        return {
            "success": True,
            "data": result
        }
        
    except HTTPException:
        raise
    except Exception as e:
        raise HTTPException(status_code=500, detail=f"批量检查配额失败: {str(e)}")

@router.post("/quotas/estimate-task")
async def estimate_task_quota(
    request: TaskQuotaEstimateRequest,
    current_user = Depends(deps.get_current_user)
):
    """估算任务所需配额"""
    
    try:
        # 构建任务参数
        task_params = {
            "service_type": request.service_type,
            "duration": request.duration,
            "resolution": request.resolution,
            "provider": request.provider,
            **request.params
        }
        
        # 估算配额需求
        estimated_checks = quota_manager.estimate_task_quotas(current_user.id, task_params)
        
        # 检查所有配额
        is_vip = getattr(current_user, 'is_vip', False)
        result = quota_manager.check_multiple_quotas(current_user.id, estimated_checks, is_vip)
        
        return {
            "success": True,
            "data": {
                "task_params": task_params,
                "estimated_quotas": estimated_checks,
                "quota_check": result,
                "can_proceed": result["can_proceed"]
            }
        }
        
    except Exception as e:
        raise HTTPException(status_code=500, detail=f"估算任务配额失败: {str(e)}")

@router.get("/quotas/usage-history")
async def get_usage_history(
    quota_type: Optional[str] = Query(None, description="配额类型过滤"),
    days: int = Query(7, description="查询天数"),
    current_user = Depends(deps.get_current_user)
):
    """获取配额使用历史"""
    
    try:
        # 这里应该从数据库获取实际的历史数据
        # 目前返回模拟数据
        
        from datetime import timedelta
        
        history_data = {
            "user_id": current_user.id,
            "days": days,
            "quota_type": quota_type,
            "history": []
        }
        
        # 生成模拟历史数据
        for i in range(days):
            date = datetime.now() - timedelta(days=i)
            
            day_data = {
                "date": date.strftime("%Y-%m-%d"),
                "quotas": {}
            }
            
            # 如果指定了配额类型，只返回该类型
            if quota_type:
                try:
                    quota_enum = QuotaType(quota_type)
                    usage = quota_manager._get_mock_usage(current_user.id, quota_enum) * (0.8 + i * 0.1)
                    day_data["quotas"][quota_type] = usage
                except ValueError:
                    raise HTTPException(status_code=400, detail=f"无效的配额类型: {quota_type}")
            else:
                # 返回所有配额类型的数据
                for qt in QuotaType:
                    usage = quota_manager._get_mock_usage(current_user.id, qt) * (0.8 + i * 0.1)
                    day_data["quotas"][qt.value] = usage
            
            history_data["history"].append(day_data)
        
        return {
            "success": True,
            "data": history_data
        }
        
    except HTTPException:
        raise
    except Exception as e:
        raise HTTPException(status_code=500, detail=f"获取使用历史失败: {str(e)}")

@router.get("/quotas/alerts")
async def get_quota_alerts(
    current_user = Depends(deps.get_current_user)
):
    """获取配额告警信息"""
    
    try:
        is_vip = getattr(current_user, 'is_vip', False)
        summary = quota_manager.get_quota_summary(current_user.id, is_vip)
        
        alerts = []
        
        # 检查所有配额状态
        for quota_type, quota_data in summary["quotas"].items():
            status = quota_data["status"]
            usage_percentage = quota_data["usage_percentage"]
            
            if status == QuotaStatus.EXCEEDED.value:
                alerts.append({
                    "type": "error",
                    "quota_type": quota_type,
                    "message": f"{quota_type} 已超出限额",
                    "usage_percentage": usage_percentage,
                    "action_required": True
                })
            elif status == QuotaStatus.WARNING.value:
                alerts.append({
                    "type": "warning",
                    "quota_type": quota_type,
                    "message": f"{quota_type} 使用量已达到 {usage_percentage:.1%}",
                    "usage_percentage": usage_percentage,
                    "action_required": False
                })
        
        return {
            "success": True,
            "data": {
                "alerts": alerts,
                "total_alerts": len(alerts),
                "has_critical": any(alert["type"] == "error" for alert in alerts),
                "timestamp": datetime.now().isoformat()
            }
        }
        
    except Exception as e:
        raise HTTPException(status_code=500, detail=f"获取配额告警失败: {str(e)}")

# 管理员接口
@router.get("/admin/quotas/users/{user_id}")
async def admin_get_user_quota(
    user_id: int,
    current_user = Depends(deps.get_current_user_optional)
):
    """管理员获取用户配额信息"""
    
    # 这里可以添加管理员权限检查
    # if not current_user or not current_user.is_admin:
    #     raise HTTPException(status_code=403, detail="需要管理员权限")
    
    try:
        # 假设从数据库查询用户VIP状态
        is_vip = False  # 这里应该查询实际的用户数据
        
        summary = quota_manager.get_quota_summary(user_id, is_vip)
        
        return {
            "success": True,
            "data": {
                "user_id": user_id,
                "summary": summary,
                "timestamp": datetime.now().isoformat()
            }
        }
        
    except Exception as e:
        raise HTTPException(status_code=500, detail=f"获取用户配额信息失败: {str(e)}")

@router.get("/admin/quotas/overview")
async def admin_quota_overview(
    current_user = Depends(deps.get_current_user_optional)
):
    """管理员配额总览"""
    
    # 管理员权限检查
    # if not current_user or not current_user.is_admin:
    #     raise HTTPException(status_code=403, detail="需要管理员权限")
    
    try:
        # 这里应该查询所有用户的配额统计
        # 目前返回模拟数据
        
        overview = {
            "total_users": 1250,
            "active_users_today": 89,
            "quota_violations": 12,
            "cost_alerts": 5,
            "top_usage_types": [
                {"quota_type": "video_generation", "total_requests": 2456},
                {"quota_type": "image_generation", "total_requests": 1832},
                {"quota_type": "image_editing", "total_requests": 645}
            ],
            "daily_costs": {
                "total": 1245.67,
                "average_per_user": 14.32
            },
            "timestamp": datetime.now().isoformat()
        }
        
        return {
            "success": True,
            "data": overview
        }
        
    except Exception as e:
        raise HTTPException(status_code=500, detail=f"获取配额总览失败: {str(e)}")